import React, { Component } from 'react';

import {
    HashRouter as Router,
    Route,
    Switch,
    withRouter,
    Redirect
} from 'react-router-dom';
import { inject, observer } from 'mobx-react';
import { toJS } from 'mobx';
import { RouteLayout } from 'weaver-mobile-page';
import {
    Tools, Modal, Bubble
} from 'weaver-mobile';
import Share from './share';
import New from './new';
import Summary from './summary';
import Plan from './plan';
import Detail from './detail';
import Header from './header';
import Org from './org';
import WeaAccordion from '../../../public/accordion/index';
import { WrMenu, WrOperateLog, WrAlertPage, WrFeedback, BackTop, WrShow } from '../../../public'
import { Files } from '../coms'
import { addKeyboardFocusScrollEvent } from '../../../util'

const getLabel = Tools.getLabel;
const alert = Modal.alert;
/*
我的报告首页
*/
@inject('planViewStore')
@withRouter
@observer
class PlanView extends Component {
    constructor(props) {
        super(props);
        this.state = {
            windowHeight: window.innerHeight,
            scrollTop: 0,
        };
        this.store = this.props.planViewStore;
    }
    componentWillMount() {
        let query = this.props.location.search.replace('?', '')
        if (query === 'myReport') {
            this.refreshPage(query)
        } else {
            this.setQueryParams()
            this.store.getPlanView();//传入url传来的planid。
            addKeyboardFocusScrollEvent()
        }

    }

    componentWillReceiveProps(nextProps) {
        //    this.store.scrollIndex2Height()
        this.setQueryParams()
        let query = nextProps.location.search ? nextProps.location.search.replace('?', '') : ''
        this.refreshPage(query)
    }
    refreshPage = (query) => {
        if (query === 'myReport') {
            this.store.setState({
                resourceid: '', urlPlanId: ''
            })
            this.props.history.push("/planHome/planView/index")
            this.store.getPlanView()
            // window.history.go(0)
        }
    }


    render() {
        const { datas } = this.store.planLog;
        const { history, menuData } = this.props
        const {
            year, type1, type2,
            resourceid,
            resourcename,
            files,
            fblist,
            canedit,
            canaudit,
            canreset,
            candel,
            canshare,
            errorMsg,
            fileids,
            fileStore,
            maxsize,
            logStore,
            detailLayoutStore,
            newLayoutStore,
            auditList,
            isLoading,
            category,
            isshowsummary,
            isshowplan
        } = this.store;
        const preClas = 'workrelate-mobile-plan-planview';
        const pathname = this.props.location.pathname
        let backTopTarget = ''
        if (pathname) {
            backTopTarget = pathname.indexOf("log") > -1 ? "wm-list-view-page-modal-scrollview" : "workrelate-mobile-plan-planview-content"
        }

        let Index = () => {
            return (

                <div className="workrelate-mobile-plan-planview-index roll" style={{ backgroundColor: ' #F3F7FE', height: errorMsg != '' ? '100%' : '' }}>

                    {errorMsg != ''
                        ? <WrAlertPage show={true} msg={errorMsg}></WrAlertPage>
                        : <div >

                            {isshowsummary!='0' && <WeaAccordion
                                classStyle={"wea-workrelate-mobile-accordion-is-first"}
                                title={`${getLabel('508992', '{0}年').replace("{0}", year)}${type2}${type1 == 1 ? getLabel('509037', '月工作总结') : getLabel('509038', '周工作总结')}`}
                            >
                                <Summary />
                            </WeaAccordion>}

                            {isshowplan!='0' && <WeaAccordion title={this.getPlanAccordionTitle()}>
                                <Plan />
                            </WeaAccordion>}

                            <WeaAccordion title={getLabel(22194, '相关附件')}>
                                <Files
                                    category={category}
                                    canedit={canedit}
                                    fileStore={fileStore}
                                    files={files}
                                    maxsize={maxsize}
                                    onChange={this.onFilesChange}
                                    planid={this.store.planid}
                                />
                            </WeaAccordion>
                            {type1 == '2' ? "" : <WeaAccordion title={getLabel(24969, '相关链接')}>
                                {this.store.isperformance &&
                                    <div className={`${preClas}-relate-link`}>
                                        <a
                                            href="javaScript:void(0)"
                                            onClick={(e) => this.props.history.push(`/performance/accessView?year=${year}&type1=1&type2=${type2}&resourceid=${resourceid}`)}
                                            title={`${resourcename}${getLabel('508616', '目标绩效考核')}(${year}-${type2})`}
                                        >
                                            {`${resourcename}${getLabel('508616', '目标绩效考核')}(${year}-${type2})`}
                                        </a>
                                    </div>
                                }
                            </WeaAccordion>}

                        </div>}
                </div>
            );
        }


        return (

            <BackTop
                visibilityHeight={this.props.location.pathname.indexOf("/planView/index") > -1 ? 200 : 999999}
                modal
                target={backTopTarget}

            >
                <div className={`${preClas} workrelate-roll`} style={{ height: this.state.windowHeight }}>
                    <Header showTitle={this.props.location.pathname.indexOf("/org") > -1 ? false : true} />
                    <WrShow show={!isLoading}>

                        <div className={`${preClas}-content roll`} style={{ height: this.state.windowHeight - 124 }}>


                            <Route
                                name="log"
                                breadcrumbName="log"
                                path="/planHome/planView/log"
                                render={() => {
                                    // return <Log />;
                                    return <div>
                                        <WrOperateLog
                                            logStore={logStore}
                                            handleRefresh={this.handleLogRefresh}
                                            handleEndReached={this.handleLogEndReached}
                                        ></WrOperateLog>
                                    </div>
                                }}
                            />
                            <Route
                                name="share"
                                breadcrumbName="share"
                                path="/planHome/planView/share"
                                render={() => {
                                    return <Share />;
                                }}
                            />

                            <Route
                                name="feedback"
                                breadcrumbName="feedback"
                                path="/planHome/planView/feedback"
                                render={() => {
                                    return <WrFeedback
                                        fbList={fblist}
                                        fbReplyStore={this.store.fbReply}
                                        // leftConfig={[{ type: 'blog-biaoqing' }]}
                                        onSubmit={(datas) => {
                                            const { text } = datas
                                            this.store.saveFeedback(text)
                                        }}
                                    />;
                                }}
                            />
                            <Route
                                name="org"
                                breadcrumbName="org"
                                path="/planHome/planView/org"
                                render={() => {
                                    return <Org />;
                                }}
                            />

                            <Route
                                name="index"
                                path="/planHome/planView/index"
                                render={Index}
                            />
                            <Route
                                name="audit-index"
                                path="/planHome/planAudit/planView"
                                render={Index}
                            />
                            <Route
                                name="audit-index"
                                path="/planHome/planResult/planView"
                                render={Index}
                            />

                            <Route
                                key={detailLayoutStore.id}
                                path={detailLayoutStore.path}
                                render={() => (
                                    <RouteLayout>
                                        <Detail key='detail'></Detail>
                                    </RouteLayout>
                                )}
                            />
                            <Route
                                key={newLayoutStore.id}
                                path={newLayoutStore.path}
                                render={() => (
                                    <RouteLayout>
                                        <New key='new'></New>
                                    </RouteLayout>

                                )}
                            />
                        </div>

                        <WrMenu
                            show={this.isShowMenu()}
                            data={menuData}
                            onSelect={val => this.props.history.push(val.props.path)}
                            buttonData={this.indexBottomMenu()}
                            _width={'60px'}
                        />
                    </WrShow>
                </div>
            </BackTop>
        );
    }
    //是否展示底部菜单
    isShowMenu = () => {
        let shouldShowMenuUrls = [
            '/index', '/share', 'org'
        ]
        return shouldShowMenuUrls.some((url) => {
            return this.props.location.pathname.indexOf(url) > -1
        })
    }
    //处理url参数
    setQueryParams = () => {
        let query = this.props.location.search ? this.props.location.search.replace('?', '') : ''
        this.store.urlPlanId = ''
        if (query != '') {
            // this.store.setState({planid:'',year:'',type1:'',type2:'',resourceid:''})
            let querys = query.split('&')
            if (querys.length > 0) {
                querys.map(q => {
                    let fields = q.split("=")
                    if (fields.length > 1) {
                        let f = fields[0]
                        let v = fields[1]
                        this.store[f] = v
                        if (f == 'planid') {
                            this.store.urlPlanId = v
                        }
                    }
                })
            }
        }
    }
    //下拉刷新
    handleLogRefresh = () => {
        // this.store.logStore.clearData();
        this.store.planLog = {
            planid: '',
            datas: [],
            lastcount: 0,
            lastid: '',
            status: '',
            logType: 'all',
        }
        this.store.getPlanLog(true)
    }

    //底部加载
    handleLogEndReached = () => {
        this.store.getPlanLog(false)
    }

    //获取计划accordion标题
    getPlanAccordionTitle = () => {
        let { year, type1, type2 } = this.store
        let showMonth = type2 == 12
            ? 1
            : parseInt(type2) + 1;
        let showYear = type2 == 12
            ? parseInt(year) + 1
            : year;
        if (("" + showMonth).length < 2) {
            showMonth = "0" + showMonth
        }
        let borderMonthTitle = `${getLabel('508992', '{0}年').replace("{0}", showYear)}${showMonth}${getLabel('18136', '月工作计划')} `

        let borderWeekTitle = `${getLabel('508992', '{0}年').replace("{0}", showYear)}${parseInt(type2) + 1}${getLabel('30842', '周工作计划')} `

        return type1 == 1 ? borderMonthTitle : borderWeekTitle
    }

    //附件变动事件
    onFilesChange = (ids, files) => {
        this.setState({ files, fileids: ids });
        this.store.setState({ files, fileids: ids.toString() })
        this.store.saveOrSumbit('save', false);
    }


    //alertModal
    alertModal = (onOk, title) => {
        alert(getLabel('386786', '信息确认'), title, [
            { text: getLabel(31129, '取消'), onPress: () => { } },
            {
                text: getLabel(826, '确定'),
                onPress: () => {
                    if (onOk) {
                        onOk()
                    }
                },
            },
        ])
    }
    //检查必填
    checkIsMust=()=>{
        const {summaryin,summarymap} = this.store
        let flag = false
        summaryin.forEach((v)=>{
            summarymap.list.forEach(p=>{
                if(p.ismust==1 && (!v[p.fieldname]|| v[p.fieldname]=='' )){
                    flag = true
                }
            })
        })
        return flag
    }

    //保存
    savePlanView = () => {
        if(!this.checkIsMust()){
            this.store.saveOrSumbit('save', true);
        }else{
            Bubble.warning(getLabel('509065', '请输入必填项'));
        }
    };
    //提交
    submitPlanView = () => {
        if(!this.checkIsMust()){
            this.alertModal(() => {
                this.store.saveOrSumbit('submit', true)
            }, getLabel('509013', '确认提交此报告吗？'))
        }else{
            Bubble.warning(getLabel('509065', '请输入必填项'));
        }
        
    };
    //重置
    resetPlanView = () => {

        this.alertModal(() => {
            this.store.resetPlan()
        }, getLabel('509114', '确认重新编写吗？'))


    };
    //删除
    deletePlanView = () => {
        let _ = this
        this.alertModal(() => {
            const response = this.store.deletePlanView();
            response.then(res => {
                if (res.api_status == '1') {
                    _.props.history.push("/planHome/planView/index?myReport")
                } else {
                    Bubble.error(getLabel('508818', '接口调用失败！'), 3, null, null, null, false);
                }
            })
        }, getLabel('509113', '确认删除此报告吗？'))

    };
    //分享
    sharePlanView = () => {
        this.props.history.push('/planHome/planView/share');
    };
    //批准
    auditPlan = (operation, planid) => {
        this.alertModal(() => {
            this.store.auditPlan(operation, planid)
        }, "approve" == operation ? getLabel('508908', '确认批准此报告？') : getLabel('508912', '确认退回此报告？'))

    }

    //首页下面的按钮
    indexBottomMenu = () => {
        const { canaudit, candel, canedit, canreset, canshare } = this.store;
        let menus = [];
        if (this.props.location.pathname.indexOf("org") > -1
            ||this.props.location.pathname.indexOf("share") > -1
        ) {
            
        } else {
            canaudit &&
                menus.push({
                    content: getLabel(142, '批准'),
                    onClick: () => {
                        this.auditPlan("approve", this.store.planid);
                    },
                });
            canaudit &&
                menus.push({
                    content: getLabel(236, '退回'),
                    onClick: () => {
                        this.auditPlan("return", this.store.planid);
                    },
                });
            canedit &&
                menus.push({
                    content: getLabel(86, '保存'),
                    onClick: () => {
                        this.savePlanView();
                    },
                });
            canedit &&
                menus.push({
                    content: getLabel(615, '提交'),
                    onClick: () => {
                        this.submitPlanView();
                    },
                });
            candel &&
                menus.push({
                    content: getLabel(91, '删除'),
                    onClick: () => {
                        this.deletePlanView();
                    },
                });
            canreset &&
                menus.push({
                    content: getLabel(2022, '重置'),
                    onClick: () => {
                        this.resetPlanView();
                    },
                });
            canshare &&
                menus.push({
                    content: getLabel(119, '共享'),
                    onClick: () => {
                        this.sharePlanView();
                    },
                });
        }

        return menus;
    };
}

export default PlanView;
